package com.lzy.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.session.SessionManagementFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

public class SessionFilter extends GenericFilterBean {
	
	private String loginUrl = "/login";
	
	private String loginSuccessUrl = "/home/index";
	
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	
	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}
	
	public String getLoginUrl() {
		return loginUrl;
	}

	public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		HttpSession session = request.getSession();
		Object securityContext = session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
		
//		if(securityContext != null){
//			redirectStrategy.sendRedirect(request, response, loginSuccessUrl);
//		}else{
//			redirectStrategy.sendRedirect(request, response, getLoginUrl());
//		}
		
//		if (token instanceof AnonymousAuthenticationToken) {
//			redirectStrategy.sendRedirect(request, response, getLoginUrl());
//		}
		
		chain.doFilter(request, response);
	}

}
